# -*- coding: utf-8 -*-
# Copyright 2011-2012 MagiCycles.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import re
import os
import sys
import logging


DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
PYGMENTS_PATH = os.path.join(DIR_PATH, 'pygments.zip')

sys.path.insert(0, PYGMENTS_PATH)
from pygments import highlight
from pygments.lexers import get_lexer_by_name, get_all_lexers, guess_lexer
from pygments.formatters import HtmlFormatter
from pygments.styles import get_all_styles


divstyles = "word-wrap:break-word;white-space: pre;\
border:1px solid #BBBBBB;font-size: 9pt;\
line-height:125%;margin:10px 0 10px 0;"

prestyles = "white-space:pre-wrap;white-space: -moz-pre-wrap;white-space: \
-pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;\
padding:0.99em;"

re_code = re.compile(
    r'<(pre|div) class="codehl"(\slang="(?P<lang>\S+)"){0,1}(\shlstyle="(?P<style>\S+)"){0,1}>(?P<source>.+?)</(pre|div)>'
    , re.DOTALL)

languages = [lexer[1][0] for lexer in get_all_lexers()]
languages.sort()
styles = list(get_all_styles())


class HighlightMiddleware(object):
    def process_response(self, request, response):
        content = response.content
        if not isinstance(content, unicode):
            content = unicode(content, 'utf-8')
        matches = re_code.finditer(content)
        for match in matches:
            try:
                all = match.group(0)
                lang = match.group('lang') or 'python'
                style = match.group('style') or 'default'
                source = match.group('source')

                newsource, css = make_hightlist(source, lang, style, True)
                content = content.replace(all, newsource)
            except Exception, e:
                logging.exception(e)
                raise e

        response.content = content
        return response


def make_hightlist(content, lang=None, style="default", noclasses=False):
    if lang:
        lexer = get_lexer_by_name(lang)
    else:
        lexer = guess_lexer(content)

    if noclasses:
        css = ''
    else:
        css = r'<style type="text/css"><!--'
        css += (HtmlFormatter(style=style,
            cssstyles=divstyles,
            prestyles=prestyles).get_style_defs('.highlight'))
        css += r'--></style>'

    new = highlight(content, lexer, HtmlFormatter(style=style,
        cssstyles=divstyles,
        prestyles=prestyles,
        noclasses=noclasses))

    return new, css
